package com.auto.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupClient {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    //初始化参数
    public GroupClient() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将socketChannel注册到selector中
        socketChannel.register(selector, SelectionKey.OP_READ);
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok...");
    }

    /**
     * 向服务器发送消息
     *
     * @param info
     */
    public void sendInfo(String info) {
        info = username + " 说：" + info;
        try {
            //发送消息
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取服务器发送的数据
     */
    public void readInfo() {
        try {
            int count = selector.select();
            if (count > 0) {//有事件发生的通道
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
                while (keyIterator.hasNext()) {
                    SelectionKey selectionKey = keyIterator.next();
                    if (selectionKey.isReadable()) {//如果发生了读事件
                        //获取通道
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //将通道中数据读到缓冲区中
                        socketChannel.read(byteBuffer);
                        String msg = new String(byteBuffer.array());
                        //trim()方法去除头尾字符串
                        System.out.println(msg.trim());
                    }
                    //手动删除selectionKey，以防止重复操作
                    keyIterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        final GroupClient groupClient = new GroupClient();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    //读取数据
                    groupClient.readInfo();
                    try {
                        //每隔3秒读取一次服务端数据
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()){
            String info = sc.nextLine();
            //发送数据
            groupClient.sendInfo(info);
        }
    }
}
